<template>
  <BasicDrawer
    :destroyOnClose="true"
    v-bind="$attrs"
    @register="registerDrawer"
    title="客户签字"
    :showFooter="true"
    width="680px"
    @ok="onSave"
    okText="确认"
    :maskClosable="false"
  >
    <template #centerFooter>
      <a-button danger @click="onClear">重新签名</a-button>
    </template>

    <div>客户签名：</div>
    <div
      ref="el"
      style="border-radius: 6px; border: 1px solid #e2e2e2; margin: 8px 0; padding: 8px"
    >
      <div :key="refreshKey" class="w-full">
        <vue-esign ref="esignRef" />
      </div>
    </div>
    <div>签名即代表知悉并同意，请谨慎填写！</div>
  </BasicDrawer>
</template>

<script setup>
  import { defineOptions, reactive, ref } from 'vue';

  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';

  import { useMessage } from '@/hooks/web/useMessage';
  import { POST } from '@/api/http.js';
  import VueEsign from 'vue-esign';
  import { useResizeObserver } from '@vueuse/core';

  defineOptions({ name: 'OrderSignature' });

  const emit = defineEmits(['complete']);
  const state = reactive({ title: '' });

  const refreshKey = ref(0);
  const el = ref(null);

  const esignRef = ref(null);
  const orderHeader = ref([]);

  const { createMessage } = useMessage();

  const [registerDrawer, { closeDrawer }] = useDrawerInner(async ({ orderHeader: header }) => {
    orderHeader.value = header;
    console.log(header);
  });

  function onClear() {
    esignRef.value.reset();
  }

  async function onSave() {
    const { memberCode, masterOrderSn, typeCode, id, storeCode } = orderHeader.value;
    const signName = await esignRef.value.generate();
    if (typeCode) {
      // 还款签名
      await POST('/membership/updateRepaymentSignName', {
        id,
        memberCode,
        typeCode,
        storeCode,
        signName,
      });
    } else {
      await POST('/cashier/updateShopOrderSignName', { memberCode, masterOrderSn, signName });
    }
    createMessage.success('订单已签名');
    emit('complete');
    closeDrawer();
  }

  useResizeObserver(el, (entries) => {
    const entry = entries[0];
    if (entry) {
      refreshKey.value = Date.now();
    }
  });
</script>

<style lang="less" scoped>
  .card {
    margin: 8px 0 46px;
    padding: 12px;

    .c-title {
      display: flex;
      flex-direction: row;
      align-items: center;
      column-gap: 8px;
      color: #091f3d;
      font-size: 15px;
      font-weight: 600;
    }

    .c-body {
      margin-top: 16px;

      .label {
        color: #acb4bf;
      }

      .value {
        color: #091f3d;
      }
    }
  }
</style>
